<?php
namespace admin\controllers;


use admin\models\UserExperience;
use Yii;
use yii\data\Pagination;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

/**
 * Created by PhpStorm.
 * User: 沈小鱼
 * Date: 2016/7/26
 * Time: 19:37
 */
class ExperienceController extends BaseController{



    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['add','list','del'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                ],
            ],
        ];
    }



    public function actionList(){
        $user_id = Yii::$app->request->get('user_id');
        $data = UserExperience::find()->where('mu_id='.$user_id);
        $experiencePages = new Pagination([
            'totalCount' =>$data->count(),
            'pageSize' => '5',
            'pageSizeParam' => false,
        ]);
        $experiences = $data->offset($experiencePages->offset)->limit($experiencePages->limit)->all();
        return $this->renderPartial('list',[
            'experiencePages'=>$experiencePages,
            'experiences'=>$experiences,
        ]);
    }


    public function actionAdd(){
        $admin = Yii::$app->user->identity->getId();
        if(empty($admin)){
            return $this->showResult(302,'用户已登出');
        }
        $user_id = Yii::$app->request->get('id');
        if(empty($user_id)){
            return $this->showResult(301,'读取用户信息失败');
        }
        $experienceArr = Yii::$app->request->post('UserExperience');
        if(empty($experienceArr['me_id'])){
            $experience = new UserExperience();
        }else{
            $experience = UserExperience::findOne($experienceArr['me_id']);
        }
        $experience->attributes = $experienceArr;
        $experience->mu_id = $user_id;
        if(!$experience->save()){
            return $this->showResult(400,'保存失败');
        }else{
            return $this->showResult(200,'保存成功');
        }
    }

    public function actionDel(){
        $me_id = Yii::$app->request->post('me_id');
        if(empty($me_id)){
            return $this->showResult(301,'未获取到经历信息');
        }
        $admin = Yii::$app->user->identity;
        if(empty($admin)){
            return $this->showResult(302,'您的登录信息已失效，请重新登录');
        }
        $experience = UserExperience::findOne($me_id);
        if(empty($experience)){
            return $this->showResult(301,'该条记录已不存在');
        }
        $row = Yii::$app->db->createCommand('delete from mm_user_experience WHERE me_id='.$me_id)->execute();
        if(!empty($row)){
            return $this->showResult(200,'删除成功');
        }else{
            return $this->showResult(400,'删除失败');
        }
    }

}